package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import entity.Comment;
import entity.Users;
import entity.Video;
import net.sf.json.JSONObject;
import service.CategoryService;
import service.CommentService;
import service.UsersService;
import service.VideoListService;
import service.VideoService;

@Controller
@RequestMapping("/admin")
public class AdminController {
	
	@Autowired
	VideoService videoService;
	@Autowired
	UsersService usersService;
	@Autowired
	CategoryService categoryService;
	@Autowired
	VideoListService videoListService;
	@Autowired
	CommentService commentService;
	
	//进入管理界面
	@RequestMapping("/center")
	public String center(HttpServletRequest request, Model model) {
		String username = (String) request.getSession().getAttribute("username");  
		Users login_user = usersService.findByUserName(username);  //防止注入攻击
		if(login_user.getType() == 2) {  //如果是管理员
			List<Comment> comments = commentService.findByState(1);
			List<Video> videos = videoService.findByState(4);
			model.addAttribute("videos", videos);
			model.addAttribute("comments", comments);
			return "/page/admin_verify";
		} else {
			return "";
		}
	}
	
	//获取视频的详细信息
	@RequestMapping("/each_video")
	public void each_video(int id, HttpServletResponse response) {
		Video video = videoService.findById(id);
		
		Map<String, String> videoMsg = new HashMap<String, String>();
		videoMsg.put("name", video.getName());
		videoMsg.put("intro", video.getIntro());
		videoMsg.put("categoryName", video.getCategory().getName());
		videoMsg.put("url", video.getUrl());
		videoMsg.put("state", String.valueOf(video.getVideoState().getId()));
		videoMsg.put("id", String.valueOf(video.getId()));
	
		//将json所需的包放到lib里面,将list转换为json
		//如果只是一个对象用JSONObject，如果是集合用JSONArray
		JSONObject json=JSONObject.fromObject(videoMsg);
		//响应前台页面
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/json");
 
		PrintWriter out;
		try {
			out = response.getWriter();
			out.println(json);//打印json,为了前台页面获取
			out.flush();//刷新流
			out.close();//关闭流 
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("单个视频读入成功");
	}
	
	//修改视频的状态
	@RequestMapping("/save")
	public String save_video(int videoStateId, int videoId, HttpServletResponse response) {
		System.out.println(videoStateId);
		Video video = videoService.findById(videoId);
		video.getVideoState().setId(videoStateId);
		videoService.updateVideoState(video);
		return "redirect:center";
	}
	
}
